<template>
  <div :id="containerId" style="position: relative">

    <!--  ---------------------------- begin 图片左右换位置 ------------------------------------- -->
    <div class="movety-container" :style="{top:top+'px',left:left+'px',display:moveDisplay}" style="padding:0 8px;position: absolute;z-index: 91;height: 32px;width: 104px;text-align: center;">
      <div :id="containerId+'-mover'" :class="showMoverTask?'uploadty-mover-mask':'movety-opt'" style="margin-top: 12px">
        <a @click="moveLast" style="margin: 0 5px;"><a-icon type="arrow-left" style="color: #fff;font-size: 16px"/></a>
        <a @click="moveNext" style="margin: 0 5px;"><a-icon type="arrow-right" style="color: #fff;font-size: 16px"/></a>
      </div>
    </div>
    <!--  ---------------------------- end 图片左右换位置 ------------------------------------- -->

    <!-- :showUploadList="false"  -->
    <a-upload
      name="file"
      :multiple="multiple"
      :action="uploadAction"
      :headers="headers"
      :data="{'biz':bizPath}"
      :fileList="fileList"
      :beforeUpload="beforeUpload"
      @change="handleChange"
      :remove="removeData"
      :disabled="disabled"
      :returnUrl="returnUrl"
      :listType="complistType"
      @preview="handlePreview"
      :class="{'uploadty-disabled':disabled}">
      <template v-if="!disabled">
        <div v-if="showToast">
          <div style="color: #f5222d;margin-bottom: 10px;">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</div>
        </div>
        <div v-if="isImageComp">
          <a-icon type="plus" />
          <div class="ant-upload-text">{{ text }}</div>
        </div>
        <a-button v-else-if="buttonVisible">
          <a-icon type="upload" />{{ text }}
        </a-button>
      </template>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img
        alt="example"
        style="width: 100%"
        :src="previewImage"
        @click="onPreview(previewImage)" />
    </a-modal>
    <!-- 图片或pdf 预览/下载选择 -->
    <a-modal
      title="请选择预览或下载"
      :visible="prebtnVisible"
      :footer="null"
      @cancel="prebtnVisible = false"
      :width="240"
    >
      <div style="text-align: center;">
        <a-button shape="circle" icon="search" @click="filePreview"/>
        <a-divider type="vertical"/>
        <a-button shape="circle" icon="download" @click="downloadFile"/>
      </div>
    </a-modal>
    <watermark ref="watermarks" @ok="downloadOK"/>
    <!-- 文件展示 -->
    <!-- <div v-for="(item,index) in fileList" :key="index">
      <img :src="item.url" alt="" srcset="">
      {{item.name}}
      <div>
        删除
      </div>
    </div> -->
  </div>
</template>

<script>

import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { getFileAccessHttpUrl, getAction } from '@/api/manage';
import watermark from '@/views/erp/hr/certificatefile/companyQualification/modules/watermark.vue'
import PreviewPdf from '@/utils/previewPdfPublic'
import { axios } from '@/utils/request'
import { mapGetters } from 'vuex'
const FILE_TYPE_ALL = 'all'
const FILE_TYPE_IMG = 'image'
const FILE_TYPE_TXT = 'file'
const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10);
}
var myFillName = null
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    let reg = new RegExp('\\\\', 'g');
    path = path.replace(reg, '/');
  }
  return path.substring(path.lastIndexOf('/') + 1);
}
  export default {
    name: 'JUpload',
    components: {
      watermark
    },
    data() {
      return {
        previewImg: {
          imgList: [], // 所有图片数组
          index: 0, // 当前点击的图片的索引
          infinite: true, // 是否可以循环切换
          popup: false // 弹窗的显示隐藏
        },
        uploadAction: window._CONFIG['domianURL'] + '/api/erpmng/sys/common/upload',
        headers: {},
        fileList: [],
        newFileList: [],
        uploadGoOn: true,
        previewVisible: false,
        prebtnVisible: false,
        fileInfo: {},
        // ---------------------------- begin 图片左右换位置 -------------------------------------
        previewImage: '',
        containerId: '',
        top: '',
        left: '',
        moveDisplay: 'none',
        showMoverTask: false,
        moverHold: false,
        currentImg: ''
        // ---------------------------- end 图片左右换位置 -------------------------------------
      }
    },
    props: {
      showToast: {
        type: Boolean,
        required: false,
        default: true
      },
      // 是否展示下载按钮
      showDownLoadBtn: {
        type: Boolean,
        required: false,
        default: true
      },
      text: {
        type: String,
        required: false,
        default: '点击上传'
      },
      // 限制文件格式
      fileFormat: {
        type: String,
				required: false,
				default: ''
      },
      // 文件大小,最小单位M
      fillSize: {
        type: [String, Number],
				required: false,
				default: ''
      },
      filePdf: {
        type: Boolean,
        required: false,
        default: false
      },
      fileType: {
        type: String,
        required: false,
        default: FILE_TYPE_ALL
      },
      // 只支持上传单个文件, 默认支持上传多个文件
      isSingle: {
        type: Boolean,
        required: false,
        default: false
      },
      remove: {
        type: Boolean,
        required: false,
        default: true
      },
      /* 这个属性用于控制文件上传的业务路径 */
      bizPath: {
        type: String,
        required: false,
        default: 'temp'
      },
      value: {
        type: [String, Array],
        required: false
      },
      // update-begin- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
      disabled: {
        type: Boolean,
        required: false,
        default: false
      },
      // update-end- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
      // 此属性被废弃了
      triggerChange: {
        type: Boolean,
        required: false,
        default: false
      },
      /**
       * update -- author:lvdandan -- date:20190219 -- for:Jupload组件增加是否返回url，
       * true：仅返回url
       * false：返回fileName filePath fileSize
       */
      returnUrl: {
        type: Boolean,
        required: false,
        default: true
      },
      number: {
        type: Number,
        required: false,
        default: 0
      },
      buttonVisible: {
        type: Boolean,
        required: false,
        default: true
      },
      multiple: {
        type: Boolean,
        required: false,
        default: true
      },
    },
    watch: {
      value: {
        immediate: true,
        handler() {
          let val = this.value
          if (val instanceof Array) {
            if (this.returnUrl) {
              this.initFileList(val.join(','))
            } else {
              this.initFileListArr(val);
            }
          } else {
            this.initFileList(val)
          }
        }
      }
    },
    computed: {
      isImageComp() {
        return this.fileType === FILE_TYPE_IMG
      },
      complistType() {
        return this.fileType === FILE_TYPE_IMG ? 'picture-card' : 'picture'
      }
    },
    created() {
      const token = Vue.ls.get(ACCESS_TOKEN);
      // ---------------------------- begin 图片左右换位置 -------------------------------------
      this.headers = { 'Authorization': token, 'client-id': 'web', 'user-id': Vue.ls.get('user_id') || '' };
      this.containerId = 'container-ty-' + new Date().getTime();
      // ---------------------------- end 图片左右换位置 -------------------------------------
    },

    methods: {
    ...mapGetters(["userInfo"]),
      downloadOK(){

      },
      initFileListArr(val) {
        if (!val || val.length == 0) {
          this.fileList = [];
          return;
        }
        let fileList = [];
        for (var a = 0; a < val.length; a++) {
          let url = getFileAccessHttpUrl(val[a].filePath);
          fileList.push({
            uid: uidGenerator(),
            name: val[a].fileName,
            status: 'done',
            url: url,
            response: {
              status: 'history',
              message: val[a].filePath
            }
          })
        }
        this.fileList = fileList
      },
      async initFileList(paths) {
        if (!paths || paths.length == 0) {
          // return [];
          // update-begin- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
          this.fileList = [];
          return;
          // update-end- --- author:os_chengtgen ------ date:20190729 ---- for:issues:326,Jupload组件初始化bug
        }
        let fileList = [];
        let arr = paths.split(',')
        for (var a = 0; a < arr.length; a++) {
          let url = getFileAccessHttpUrl(arr[a]);
          // ---------------从后台解析文件名称 开始----------------
          let path = arr[a]
          if (path.lastIndexOf('\\') >= 0) {
            let reg = new RegExp('\\\\', 'g');
            path = path.replace(reg, '/');
          }
          // await getAction('/api/erpmng/sys/common/queryByFillName', { fillName: path.substring(path.lastIndexOf('/') + 1) }).then(res => {
          //   if (res.success) {
          //     myFillName = res.result
          //   }
          // })
          // ---------------从后台解析文件名称 结束----------------

          fileList.push({
            uid: uidGenerator(),
            name: path,
            status: 'done',
            url: url,
            response: {
              status: 'history',
              message: arr[a]
            }
          })
        }
        this.fileList = fileList
      },
      handlePathChange() {
        let uploadFiles = this.fileList
        let path = ''
        if (!uploadFiles || uploadFiles.length == 0) {
          path = ''
        }
        let arr = [];

        for (var a = 0; a < uploadFiles.length; a++) {
          // update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
          if (uploadFiles[a].status === 'done') {
            arr.push(uploadFiles[a].response.message)
          } else {
            return;
          }
          // update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
        }
        if (arr.length > 0) {
          path = arr.join(',')
        }
        this.$emit('change', path);
      },
      removeData() {
        return new Promise((resolve, reject) => {
          return resolve(this.remove);
        })
      },
      beforeUpload(file) {
        const that = this
        that.uploadGoOn = true
          var fileType = file.type;
          if (that.fileType === FILE_TYPE_IMG) {
            if (fileType.indexOf('image') < 0) {
              that.$message.warning('请上传图片');
              that.uploadGoOn = false
              return false;
            }
          }
          if (that.fileType === FILE_TYPE_TXT) {
            if (fileType.indexOf('image') !== -1) {
              that.$message.warning('请上传文件');
              that.uploadGoOn = false
              return false;
            }
          }
          // 判断类型
				var typeFile = ''
        var _data = file.name
				if (_data.indexOf('.') != -1) {
					var arr = _data.split('.')
					typeFile = '.' + arr[arr.length - 1]
				} else {
					typeFile = ''
				}
				if (this.fileFormat && (this.fileFormat.indexOf(typeFile) == -1)) {
					that.$message.warning('请上传正确的附件格式！');
          that.uploadGoOn = false
					return false
				}
          if (this.isSingle) {
            if (this.fileList.length > 0) {
              that.$message.warning('只允许上传一个附件！');
              that.uploadGoOn = false
              return false;
            }
          }
        // var pattern = /[*|\":<>[\]{}`\\()';@&$]/;
        // if (pattern.test(file.name)) {
        //   // eslint-disable-next-line no-useless-escape
        //   that.$message.warning('文件名中不能包含特殊字符:  [*|":<>[\]{}`\\()\';@&$]');
        //   that.uploadGoOn = false
        //   return false;
        // }

        // 验证文件大小
        if (this.fillSize) {
          const isSize = file.size / 1024 / 1024 < Number(this.fillSize)
          if (!isSize) {
            that.$message.error(`请上传 ${this.fillSize}MB 以内的文件`);
            that.uploadGoOn = false
            return false;
          }
        }

          // TODO 扩展功能验证文件大小
          const isFillSize = file.size / 1024 / 1024 < 500;
          if (!isFillSize) {
            that.$message.error('请上传 500MB 以内的文件');
            that.uploadGoOn = false
            return false;
          }

          // 判断文件名称是否包含空格
          const reg = new RegExp(/\s/)
          if (reg.test(file.name)) {
            that.$message.warning('文件名称包含空格，请重新选择文件上传！');
            that.uploadGoOn = false
            return false;
          }

          // 判断是否重复上传，文件名和文件后缀类型一致则认为重复上传
          if (that.fileList.length > 0) {
            let fileName = file.name.replace('=', '').replace(',', '').replace('&', '').replace('#', '').replace(/ /g, '');
            for (let index = 0; index < that.fileList.length; index++) {
              let name = that.fileList[index].name
              if (file.name.length > 50) {
                // 如果文件名超过50位则自动进行截取文件名的前50位字符，substring含头不含尾
                name = name.substring(0, 51) + name.substring(name.lastIndexOf('.'))
                fileName = fileName.substring(0, 51) + fileName.substring(fileName.lastIndexOf('.'))
              } else {
                name = name.substring(0, name.lastIndexOf('_')) + name.substring(name.lastIndexOf('.'))
              }
              if (name == fileName) {
                that.$message.warning('文件名称已存在，请勿重复上传文件！');
                that.uploadGoOn = false
                return false;
              }
            }
          }
          if (!that.uploadGoOn) {
            return false
          }
          return true;
      },
      handleChange(info) {
        if (!info.file.status && this.uploadGoOn === false) {
          info.fileList.pop();
        }
        var fileList = []
        info.fileList.forEach((value) => {
          if (value.status) {
            fileList.push(value)
          }
        })

        if(this.filePdf){
          let extList = ['pdf']          
          
          let name = info.file.name

          let fileTypeValue = name.substring(name.lastIndexOf(".")+1)

          if (!extList.find((item) => item == fileTypeValue)) {
            return this.$message.error('只能上传pdf格式的文件！')
          }
        }
        
        // let fileList = info.fileList
        if (info.file.status === 'done') {
          if (this.number > 0) {
            fileList = fileList.slice(-this.number);
          }
          if (info.file.response.success) {
            fileList = fileList.map((file) => {
              if (file.response) {
                let reUrl = file.response.message;
                file.url = getFileAccessHttpUrl(reUrl);
              }
              return file;
            });
          }
          this.$message.success(`${info.file.name} 上传成功!`);
        } else if (info.file.status === 'error') {
          this.$message.error(`${info.file.name} 上传失败.`);
        } else if (info.file.status === 'removed') {
          this.handleDelete(info.file)
        }
        this.fileList = fileList
        if (info.file.status === 'done' || info.file.status === 'removed') {
          // returnUrl为true时仅返回文件路径
          if (this.returnUrl) {
            this.handlePathChange()
          } else {
            // returnUrl为false时返回文件名称、文件路径及文件大小
            this.newFileList = [];
            for (var a = 0; a < fileList.length; a++) {
              // update-begin-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
              if (fileList[a].status === 'done') {
                var fileJson = {
                  fileName: fileList[a].name,
                  filePath: fileList[a].response.message,
                  fileSize: fileList[a].size
                };
                this.newFileList.push(fileJson);
              } else {
                return;
              }
              // update-end-author:lvdandan date:20200603 for:【TESTA-514】【开源issue】多个文件同时上传时，控制台报错
            }
            this.$emit('change', this.newFileList);
          }
        }
      },
      handleDelete(file) {
        // 如有需要新增 删除逻辑
        console.log(file)
      },
      filePreview() {
        var typeName = this.fileInfo.name.split('.')[this.fileInfo.name.split('.').length - 1]
        var imgArr = ['gif', 'jpg', 'png', 'bmp', 'jpeg', 'webp']
        if (imgArr.indexOf(typeName.toLowerCase()) > 0) {
          // 当选择的是图片的时候则需要把所有的图片全部拿出来
          // var fileList = this.$refs.upload.fileList;
          var images = []
          if (Array.isArray(this.value)) {
            this.value.map(resp => {
              images.push(resp.filePath)
            })
          } else {
            images = this.value.split(',') // 把附件变成数组
          }
          // 筛选出图片
          var imgList = images.filter(item => {
            return item.indexOf('.jpg') > 0 || item.indexOf('.png') > 0 || item.indexOf('.gif') > 0 || item.indexOf('.bmp') > 0 || item.indexOf('.jpeg') > 0 || item.indexOf('.webp') > 0
          })
          // 拼接上地址
          var imgIndex = 0
          imgList.map((item, index) => {
            // 判断点击的是哪个图片
            if (item === this.fileInfo.name) {
              imgIndex = index
            }
            imgList[index] = getFileAccessHttpUrl(item)
          })
          this.prebtnVisible = false;
          this.previewImg = {
            imgList: imgList, // 所有图片数组
            index: imgIndex, // 当前点击的图片的索引
            infinite: true, // 是否可以循环切换
            popup: true // 弹窗的显示隐藏
          }
        } else {
          if(typeName  == 'pdf'){
            let text = `${this.userInfo().orgCodeTxt}-${this.userInfo().realname}-${this.userInfo().workNo}`
            let url = window.sessionStorage.getItem('baseUrl') + '/api/erpmng/sys/common/static/' + this.fileInfo.name
            axios({
              url: url,
              params: {},
              method:'get' ,
              responseType: 'blob',
            }).then(res=>{
              new PreviewPdf({
                blob: res,
                docTitle: 'pdf',
                isAddWatermark: true, // 是否需要添加水印
                watermark: { // watermark必填 里面可以不填
                  type: 'canvas',
                  text: text,
                }
              })
            })
          } else {
            let url = this.fileInfo.response.message;
            let fileUrl = getFileAccessHttpUrl(url)
            let Base64 = require('js-base64').Base64
            //水印
            //window.open(window._CONFIG['onlinePreviewDomainURL'] + '?url=' + encodeURIComponent(Base64.encode(fileUrl))+'&watermarkTxt='+encodeURIComponent('禾美协同办公'))
            //不含水印
            window.open(window._CONFIG['onlinePreviewDomainURL'] + '?url=' + encodeURIComponent(Base64.encode(fileUrl)))
          }
        }
      },
      downloadFile() {
        var typeName = this.fileInfo.name.split('.')[this.fileInfo.name.split('.').length - 1]
        // var imgArr = ['gif', 'jpg', 'png', 'bmp', 'jpeg', 'webp']
        if (typeName == 'pdf') {
          this.$refs.watermarks.visible = true
          this.$refs.watermarks.wValue = this.fileInfo.name
        } else {
          location.href = this.fileInfo.url
        }
      },
      handlePreview(file) {
        var typeName = file.name.split('.')[file.name.split('.').length - 1]
        var imgArr = ['gif', 'jpg', 'png', 'bmp', 'jpeg', 'webp']
        if (imgArr.indexOf(typeName) > 0 || typeName == 'pdf') {
          this.prebtnVisible = true
          this.fileInfo = file
        } else {
          // location.href = file.url
          this.prebtnVisible = true
          this.fileInfo = file
        }
        // if(this.fileType === FILE_TYPE_IMG){
        //   this.previewImage = file.url || file.thumbUrl;
        //   this.previewVisible = true;
        // }else{
        //   location.href=file.url
        // }
      },
      handleCancel() {
        this.previewVisible = false;
      },
      // ---------------------------- begin 图片左右换位置 -------------------------------------
      moveLast() {
        let index = this.getIndexByUrl();
        if (index == 0) {
          this.$message.warn('未知的操作')
        } else {
          let curr = this.fileList[index].url;
          let last = this.fileList[index - 1].url;
          let arr = []
          for (let i = 0; i < this.fileList.length; i++) {
            if (i == index - 1) {
              arr.push(curr)
            } else if (i == index) {
              arr.push(last)
            } else {
              arr.push(this.fileList[i].url)
            }
          }
          this.currentImg = last
          this.$emit('change', arr.join(','))
        }
      },
      moveNext() {
        let index = this.getIndexByUrl();
        if (index == this.fileList.length - 1) {
          this.$message.warn('已到最后~')
        } else {
          let curr = this.fileList[index].url;
          let next = this.fileList[index + 1].url;
          let arr = []
          for (let i = 0; i < this.fileList.length; i++) {
            if (i == index + 1) {
              arr.push(curr)
            } else if (i == index) {
              arr.push(next)
            } else {
              arr.push(this.fileList[i].url)
            }
          }
          this.currentImg = next
          this.$emit('change', arr.join(','))
        }
      },
      getIndexByUrl() {
        for (let i = 0; i < this.fileList.length; i++) {
          if (this.fileList[i].url === this.currentImg || encodeURI(this.fileList[i].url) === this.currentImg) {
            return i;
          }
        }
        return -1;
      },

      // 预览图片
      onPreview (url) {
        // this.$viewerApi({
        // images: url
        // // options: {
        // //   initialViewIndex: 2,
        // // },
        // })
        this.previewImg = {
          imgList: [url], // 所有图片数组
          index: 0, // 当前点击的图片的索引
          infinite: true, // 是否可以循环切换
          popup: true // 弹窗的显示隐藏
        }
      }
    },
    mounted() {
      const moverObj = document.getElementById(this.containerId + '-mover');
      if (moverObj) {
        moverObj.addEventListener('mouseover', () => {
          this.moverHold = true
          this.moveDisplay = 'block';
        });
        moverObj.addEventListener('mouseout', () => {
          this.moverHold = false
          this.moveDisplay = 'none';
        });
      }

      let picList = document.getElementById(this.containerId) ? document.getElementById(this.containerId).getElementsByClassName('ant-upload-list-picture-card') : [];
      if (picList && picList.length > 0) {
        picList[0].addEventListener('mouseover', (ev) => {
          ev = ev || window.event;
          let target = ev.target || ev.srcElement;
          if (target.className == 'ant-upload-list-item-info') {
            this.showMoverTask = false
            let item = target.parentElement
            this.left = item.offsetLeft
            this.top = item.offsetTop + item.offsetHeight - 50;
            this.moveDisplay = 'block';
            this.currentImg = target.getElementsByTagName('img')[0].src
          }
        });

        picList[0].addEventListener('mouseout', (ev) => {
          ev = ev || window.event;
          let target = ev.target || ev.srcElement;
          if (target.className == 'ant-upload-list-item-info') {
            this.showMoverTask = true
            setTimeout(() => {
              if (this.moverHold === false) { this.moveDisplay = 'none'; }
            }, 100)
          }
          if (target.className == 'ant-upload-list-item ant-upload-list-item-done' || target.className == 'ant-upload-list ant-upload-list-picture-card') {
            this.moveDisplay = 'none';
          }
        })
        // ---------------------------- end 图片左右换位置 -------------------------------------
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style lang="less">
.uploadty-disabled{
  .ant-upload-list-item {
    .anticon-close{
      display: none;
    }
    .anticon-delete{
      display: none;
    }
  }
}
  //---------------------------- begin 图片左右换位置 -------------------------------------
  .uploadty-mover-mask{
    background-color: rgba(0, 0, 0, 0.5);
    opacity: .8;
    color: #fff;
    height: 28px;
    line-height: 28px;
  }
  //---------------------------- end 图片左右换位置 -------------------------------------
</style>
